using System;
using UnityEngine;

namespace Framework
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _instance;
    
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    var go = new GameObject(typeof(T).Name);
                    DontDestroyOnLoad(go);
                    _instance = go.AddComponent<T>();
                }

                return _instance;
            }
        }


        // virtual 和 abstract 
        // 都可以使用override重写
        // virtual 不是必须重写
        // abstract 必须重写, 而且必须在abstract类中
        private Action _initCb;
        public virtual void Init(Action callback = null)
        {
            _initCb = callback;
        }
        
        protected void OnInitFinish()
        {       
            if(null == _initCb)
            {
                return;
            }
            try
            {
                _initCb();
            }
            catch(System.Exception exp)
            {
                Logger.LogException(exp);
            }
        }
        
        public override string ToString()
        {
            return "MonoSingleton " + gameObject.name;
        }
    }
}

